package com.zlxtk.ling.qiGuan;

import com.zlxtk.ling.nao.InputZhongShu;
import com.zlxtk.ling.nao.OutputZhongShu;
import com.zlxtk.ling.po.InputDataDto;
import com.zlxtk.ling.po.Jue;
import com.zlxtk.ling.po.TingInputDataDto;

import java.util.UUID;

/**
 * 概念：器官
 */
public abstract class QiGuan extends Thread {

    private String id;

    public int status = 100;//器官状态，0：停止（损坏）；100：正常；值越低效果越低，值越大效果越大

    private OutputZhongShu outputZhongShu;

    public QiGuan(OutputZhongShu outputZhongShu) {
        this.id = UUID.randomUUID().toString().replaceAll("-", "");
        this.outputZhongShu = outputZhongShu;
    }

    /**
     * 器官运转
     */
    @Override
    public void run() {
        while (status != 0) {//器官损坏时停止运行

            //检测器官状态
            check();
            //获取数据
            InputDataDto data;
            try {
                data = getData();
            } catch (Exception e) {
                if (getType().equals(QiGuanType.TING)) {
                    data = new TingInputDataDto();
                }
                data = new InputDataDto<String>();
            }

            Jue jue = new Jue(getType(), id, this.status, data);

            //向中枢神经传递数据
            InputZhongShu.getInstance().update(jue);
            try {
                // yield();
                sleep(1);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    //获取器官类型
    public abstract QiGuanType getType();

    public abstract InputDataDto getData();


    /**
     * 检测器官状态
     */
    private void check() {
        if (this.id == null) {
            this.status = 0;
            return;
        }
        this.status = doCheck();
        this.status = this.status > 100 ? 100 : this.status;
        this.status = this.status < 0 ? 0 : this.status;
    }

    /**
     * 真实的检测逻辑
     *
     * @return 检测状态 0：停止（损坏）；100：正常；值越低则损坏程度越高，值越大则损坏程度越小
     */
    protected abstract int doCheck();
}
